from flask import g
from flask_restplus import Resource, Namespace, fields, marshal
from common.decorators import catch_error
from common.responses import ok
from app.user.decorators import token_required, permission_required
from app.company.model import Company
from flask import send_file
import pandas as pd
from app.user.model import User

from app.user.controller import user_download_model

from app.file.service import get_excel_file_path, json_to_dataframe

api = Namespace('company', path='/company')

company_setting_model = api.model('company', {
    'id': fields.String(description='company id'),
    'name': fields.String(description='company name'),
    'phone': fields.Integer(description='phone'),
    'address': fields.String(),
    'notes': fields.String(),

    'avatar': fields.String(),
    'home_img': fields.String(),
    'tags': fields.Raw(),
    'desc': fields.String(),
    'is_active': fields.Boolean(),
    'create_datetime': fields.DateTime(),

    # setting
    "auto_sku_sn_is_active": fields.Boolean(),
    'auto_sku_sn_prefix': fields.String(),
    'auto_sku_sn_start_index': fields.Integer(),
    'auto_sku_sn_len': fields.Integer(),

    # 过期时间
    'expired_datetime': fields.DateTime(),
    'vip_type': fields.Integer(),
    'expired_days': fields.Integer(),
    'num_of_products_limit': fields.Integer(),
    'num_of_staffs_limit': fields.Integer(),
    'num_of_warehouses_limit': fields.Integer(),

})


class CompanySettingResource(Resource):
    @catch_error
    @token_required
    def get(self):
        company = Company.query.filter_by(id=g.company_id, is_active=True).first()
        return ok(data=marshal(company, company_setting_model),
                  message='get success')

    @catch_error
    @token_required
    # @permission_required(Permissions.SYSTEM_SETTING)
    def put(self, company_id):
        """更新 company"""
        parser = api.parser()
        parser.add_argument('name', type=str, help='名称')
        parser.add_argument('address', type=str, help='地址')
        parser.add_argument('phone', type=str, help='地址')
        parser.add_argument('notes', type=str, help='备注')

        parser.add_argument('tags', type=str, help='标签', action='append')
        parser.add_argument('desc', type=str, help='描述')
        parser.add_argument('is_active', type=bool, choices=(True, False), help='描述')

        # 设置修改
        parser.add_argument('auto_sku_sn_is_active', type=bool, help='自动货号是否开启')
        parser.add_argument('auto_sku_sn_prefix', type=str, help='自动货号前缀')
        parser.add_argument('auto_sku_sn_start_index', type=int, help='自动货号当前起始位置')
        parser.add_argument('auto_sku_sn_len', type=int, help='自动货号数字长度')

        args = parser.parse_args()
        # 如果为空，则不要更新
        for key in list(args.keys()):
            if args.get(key) is None:
                del args[key]

        company = Company.query.filter_by(id=company_id).first()
        company.update(commit=True, **args)
        return ok(data=marshal(company, company_setting_model), message="update success")


class CompanyDownloadResource(Resource):
    @catch_error
    @token_required
    def get(self):
        """下载所有文件"""
        users = User.query.filter_by(company_id=g.company_id).all()
        users_json = marshal(users, user_download_model)
        df_user = json_to_dataframe(users_json)

        # 将资料保存在一个excel的不同sheet中
        excel_file_path = get_excel_file_path('全部数据')
        with pd.ExcelWriter(excel_file_path) as writer:
            df_user.to_excel(writer, sheet_name='员工', index=False)
        return send_file(excel_file_path, as_attachment=True)


# 获取公司配置 修改公司信息
api.add_resource(CompanySettingResource, '/company_setting')
api.add_resource(CompanyDownloadResource, '/download_excel')  # 下载所有文件： 包含部门，员工，合同，订单，项目，收支单
